#include "contactlist.h"
#include <QDebug>
#include <QAction>
#include <QIcon>
#include <QHostAddress>
#include "contactlistitem.h"
ContactList::ContactList(QListWidget *parent) :  QListWidget(parent)
{
    setFocusPolicy(Qt::NoFocus);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    initMenu();
}

void ContactList::initMenu()
{
    blankMenu = new QMenu();
    personMenu = new QMenu();
    QAction *addContact = new QAction("添加好友",this);
    QAction *delContact = new QAction("删除好友", this);


    personMenu->addAction(delContact);
    connect(addContact,SIGNAL(triggered()),this,SLOT(slotAddContact(ContactInfo *contactInfo)));
    connect(delContact,SIGNAL(triggered()),this,SLOT(slotDelContact()));
}
void ContactList::mousePressEvent(QMouseEvent *event)
{
    QListWidget::mousePressEvent(event);
    currentItem = this->itemAt(mapFromGlobal(QCursor::pos()));
    if(event->button()==Qt::LeftButton&&currentItem!=NULL){
         QWidget* pwig = this->itemWidget(currentItem);
         QList<ContactInfo*> contactInfoList = pwig->findChildren<ContactInfo*>();
         for (int i=0;i<contactInfoList.size();i++) {
             qDebug()<<contactInfoList[0];
             emit contactItemClick(contactInfoList[0]);
         }
    }
}
void ContactList::contextMenuEvent(QContextMenuEvent *event)
{
    QListWidget::contextMenuEvent(event);
    if(currentItem==NULL)
    {
        blankMenu->exec(QCursor::pos());
        return;
    }
     personMenu->exec(QCursor::pos());

}



void ContactList::slotAddContact(ContactInfo *contactInfo,bool isMe)
{
    ContactListItem *Contact=new ContactListItem();
    Contact->avatarPath=contactInfo->avatarPath;
    if(isMe){
        Contact->nickName->setText(contactInfo->sourceHostUserName+"(本机)");
    }else {
       Contact->nickName->setText(contactInfo->sourceHostUserName);
    }
    Contact->hostName->setText(contactInfo->sourceIp);
    contactInfo->setParent(Contact);
    Contact->contactInfo=contactInfo;
    QListWidgetItem *newItem = new QListWidgetItem();
    this->insertItem(row(currentItem),newItem);
    this->setItemWidget(newItem, Contact);


}
void ContactList::slotDelContact()
{
    delete currentItem;
}
//判断 联系人对象contactInfo是否在联系人列表contactList中
int ContactList::slotIsIncludeList(ContactInfo *contactInfo){

    int listCount= this->count();
    for (int i=0;i<listCount;i++) {
        QWidget* pwig = this->itemWidget(this->item(i));
        QList<ContactInfo*> contactInfoList = pwig->findChildren<ContactInfo*>();
        qDebug()<<contactInfoList;
        if(contactInfoList.size()>0&&contactInfoList[0]->sourceMac==contactInfo->sourceMac){
            qDebug()<<"存在"<<i;
            //列表中已存在，
            QList<QLabel*> labellist = pwig->findChildren<QLabel*>();
//            labellist[0]->setText(contactInfo->sourceHostUserName);
              labellist[1]->setText(contactInfo->sourceIp);
            return  i;
        }

    }
    return -1;
}


